package binary

import (
	"bytes"
	"io"
)

func NewBuffer(bts []byte) *Buffer {
	var buf Buffer
	buf.buf = bts
	return &buf
}

type Buffer struct {
	buf      []byte
	off      int
	flushOff int
}

func (b *Buffer) Flush() []byte {
	removed := b.buf[:b.off]
	b.buf = b.buf[b.off:]
	b.off = 0
	return removed
}

func (b *Buffer) Unread() {
	b.off = 0
}

func (b *Buffer) UnreadByte() {
	if b.off > 0 {
		b.off -= 1
	}
}

func (b *Buffer) Write(bts []byte) {
	b.buf = append(b.buf, bts...)
}

//Seek 该函数不同于Read函数，使用绝对地址进行操作
func (b *Buffer) Seek(start, end int) []byte {
	return b.buf[start:end]
}

func (b *Buffer) Read(p []byte) (n int, err error) {
	n = copy(p, b.buf[b.off:])
	b.off += n
	if n < len(p) {
		err = io.EOF
	}
	return
}

func (b *Buffer) ReadByte() (byte, error) {
	if b.off >= len(b.buf) {
		return 0, io.EOF
	}
	c := b.buf[b.off]
	b.off++
	return c, nil
}

func (b *Buffer) Bytes() []byte {
	return b.buf
}

func (b *Buffer) Offset(len int) {
	b.off += len
}

func (b *Buffer) Index(chars []byte) int {
	return bytes.Index(b.buf[b.off:], chars)
}

func (b *Buffer) Len() int {
	return len(b.buf) - b.off
}

// bytes.NewBuffer
